
/**
 * 加载购物车列表数据
 */
 let checkAllState = false
function loadCartList() {
    //获取localStorage数据
    let listStr = localStorage.getItem('JD_CART')
    let cartList = JSON.parse(listStr) || []

    //初始化模板字符串，表格头部th
    let str = `<tr>
                 <th><input type="checkbox" name="checkall" ${checkAllState?'checked':''}>全选</th>
                    <th>序号</th>
                    <th>商品图片</th>
                    <th>商品信息</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th width="100px">总价</th>
                    <th>操作</th>
                </tr>`

    //循环生成商品列表项 
    cartList.forEach(function (item) {
        let trStr = `
        <tr data-index="${item.id}" class ="item">
        <td><input type="checkbox" data-index="${item.id}" name="checksingle"  ${item.state?'checked':''}></td>  
                    <td>${item.id}</td>
                    <td><img src="${item.url}" alt=""></td>
                    <td>${item.name}</td>
                    <td>￥${item.price}</td>
                    <td> <input name="minus" type="button" value="-" ${item.num==0?'disabled':''} ><input type="text" name="amount" value="${item.num}"><input
                            type="button" name="plus" value="+"></td>
                    <td>￥${item.singlePrice}</td>
                    <td><a href="#" class="del">删除</a></td>
                </tr> `

        str += trStr //字符串拼接
    })

    //将动态生成商品列表字符串作为table的内容显示
    $('.product-list>table').html(str)
    totalPrice()
}

function onCartList() {
    //加操作
    $('table').on('click', 'input[name="plus"]', function () {
        let cartStr = localStorage.getItem('JD_CART')
        let cartList = JSON.parse(cartStr) || []
        
         let id = $(this).parent().parent().children().first().next().html()
       
        //let id = $(this).parent().parent().attr('data-index')
        let product = cartList.find(item => item.id == id)
        product.num++

        product.singlePrice = (product.num * product.price).toFixed(2) //计算价格

        //持久化存
        localStorage.setItem('JD_CART', JSON.stringify(cartList))

        //重新渲染页面
        loadCartList()

    })

    //减操作
    $('table').on('click', 'input[name="minus"]', function () {
        let cartStr = localStorage.getItem('JD_CART')
        let cartList = JSON.parse(cartStr) || []

        let id = $(this).parent().parent().attr('data-index')
        let product = cartList.find(item => item.id == id)
        product.num--

        product.singlePrice = (product.num * product.price).toFixed(2) //计算价格

        //持久化存
        localStorage.setItem('JD_CART', JSON.stringify(cartList))

        //重新渲染页面
        loadCartList()
    })
    //删除操作
    $('table').on('click', '.del', function () {
        let cartStr = localStorage.getItem('JD_CART')
        let cartList = JSON.parse(cartStr) || []
        let id = $(this).parent().parent().attr('data-index')
        //找索引号
        let index = cartList.findIndex(item => item.id == id)
        cartList.splice(index, 1)

        //持久化存
        localStorage.setItem('JD_CART', JSON.stringify(cartList))
        //重新渲染页面
        loadCartList()

    })

    //复选框
    $('table').on('click', 'input[name="checksingle"]', function () {
        let cartStr = localStorage.getItem('JD_CART')
        let cartList = JSON.parse(cartStr) || []
        let id = $(this).parent().parent().attr('data-index')

        //设置当前复选框数据
        let product = cartList.find(item => item.id == id)
        product.state = !product.state
        //全选框数据

        checkAllState = cartList.every(item => item.state == true)
        //持久化存
        localStorage.setItem('JD_CART', JSON.stringify(cartList))
        //重新渲染页面
        loadCartList()
    })
    //全选框
    $('table').on('click', 'input[name="checkall"]', function () {
        let cartStr = localStorage.getItem('JD_CART')
        let cartList = JSON.parse(cartStr) || []
        //设置全选框状态
        checkAllState = !checkAllState
        //所有复选框状态
        cartList.forEach(item => item.state = checkAllState)
        //持久化存
        localStorage.setItem('JD_CART', JSON.stringify(cartList))
        //重新渲染页面
        loadCartList()
    })
}
/**
 * 计算选中商品总价
 *   将 state为true商品singlePrice价格累加
 */
 function totalPrice() {
    let cartStr = localStorage.getItem('JD_CART')
    let cartList = JSON.parse(cartStr) || []

    let sum = 0
    cartList.forEach(item => {
        if (item.state) {
            sum += Number(item.singlePrice)
        }
    })
    $('.total-price').html(sum)
}

//跳转到商品列表页
function onProductList() {
    $('.logo').on('click', function () {
        location.href = '../pages/productlist.html'
    })
}


let oldproduct = {} //当前商品对象
/**
 * 获取商品ID
 * @returns 
 */
function getProductId() {
    let url = location.href
    //http://localhost:3000/pages/productDetail.html?id=13
    let index = url.indexOf('?') + 1
    let param = url.substring(index) //id=1
    let id = param.split('=')[1]
    return id
}

/**
 * 商品详情事件
 */
 function onProductDetail() {
    $('table').on('click', '.item', function () {
        let id = $(this).attr('data-index')
        location.href = '../pages/productDetail.html?id=' + id
    })
}

onProductDetail()
onCartList()
loadCartList()
onProductList()